import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux'
import _ from 'lodash'

import { Table, Icon, Tag, message, Modal, Popover, Button,Alert } from 'antd';
import {fetchArgs,FetchURL,fetchData,removeData,changePage} from '../../store/actions';
import FormRegion from '../../components/form-region'

class _Region extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            city:[],
            area:[],
            visible:false,
            id:null,
            user: this.props.user,
            title:'',
            modalInitial:'',
            confirmLoading: false,
            RegionLen:0
        };
        this._changePage = this._changePage.bind(this);
        this.fetchRegion=this.fetchRegion.bind(this);
        this.onSelectChange = this.onSelectChange.bind(this);
        this.reFetch = this.reFetch.bind(this);
        this.Edit = this.Edit.bind(this);
        this.delData = this.delData.bind(this);
    };
    fetchRegion(){
        const _this = this;
        let _args = Object.assign({},fetchArgs);
        _args.URL = FetchURL.REGION;
        _args.IsAuth = true;
        _args.Succ = function (res) {
            let _data = res.content;
            let _city = [];
            let _area = [];
            if(_data.length > 0) {
                _city = _data[0].cities;
                if(_city[0].areas.length > 0)
                    _area = _city[0].areas;
            }
            _this.setState({
                data:_data,
                city:_city,
                area:_area,
                RegionLen:_data.length
            })
        };
        _this.props.dispatch(fetchData(_args));
    };
    componentWillMount(){
        this.fetchRegion();
    };
    static contextType = {
        router:React.PropTypes.object
    };
    _changePage(){
        // this.props.dispatch(changePge(''));
    };
    onSelectChange(selectedRowKeys) {
        this.setState({ selectedRowKeys });
    };
    reFetch(){
        this.setState({
            visible:false,
            id:null,
            targetData:null
        });
        this.fetchRegion();
    };
    delData(e){
        e.preventDefault();
        const _t = e.target.dataset;
        this.setState({id:_t.id});
        const modalOpts = {
            title:'删除数据项',
            content: `要删除 ${_t.name} 吗？`,
            okText: ` 删除 `,
            onOk:this.delOk.bind(this)
        };
        Modal.confirm({...modalOpts})
    };
    delOk(){
        const _this = this;
        let _args = Object.assign({},fetchArgs);
        _args.Id = this.state.id;
        _args.URL = FetchURL.REGION;
        _args.IsAuth = true;
        _args.Succ = function (res) {
            message.success('删除区域成功', 1, function () {
                _this.reFetch();
                _this.setState({
                    visible:false,
                    id:null,
                    title:'',
                    modalInitial:'',
                    confirmLoading: false
                });
            });
        };
        _this.props.dispatch(removeData(_args));
    };
    addData(e){
        e.preventDefault();
        this.setState({
            visible:true,
            id:null,
            title:'新建',
            targetData:null
        });
    };
    Edit(e){
        e.preventDefault();
        const _t = e.target.dataset;
        const targetData = _.filter(this.state.data,{id: parseInt(_t.id)})[0];
        this.setState({
            user: this.props.user,
            id : _t.id,
            visible:true,
            title:'编辑',
            targetData:targetData
        });
    };
    onCancel(){
        this.setState({
            visible:false
        });
    };
    render(){
        const columns=[{
            title:'编码',
            dataIndex:'code',
            width:100
        },{
            title:'名称',
            dataIndex:'name',
            width:200
        }, {
            title:'助记符',
            dataIndex:'mnemonic',
            width:100
        }, {
            title:'状态',
            dataIndex:'status',
            width:100,
            className: 'ant-column-status',
            render:(text,record)=>{
                switch (text){
                    case 1:
                    case '1':
                        return <span style={{color:'green'}}>启用</span>;
                    case 0:
                    case '0':
                        return <span style={{color:'red'}}>未启用</span>;
                    default:
                        return <span>未知</span>;
                }
            }
        }];
        const dataLen1 = this.state.RegionLen;
        const pagination1 = {
            total:dataLen1,
            showSizeChanger:true,
            onShowSizeChange(current,pageSize){
                /*console.log('Current: ', current, '; PageSize: ', pageSize);*/
            },
            onChange(current){
                /*console.log('Current: ', current);*/
            }
        };

        const dataLen2 = this.state.data[0] && this.state.data[0].cities.length;
        const pagination2 = {
            total:dataLen2,
            showSizeChanger:true,
            onShowSizeChange(current,pageSize){
                /*console.log('Current: ', current, '; PageSize: ', pageSize);*/
            },
            onChange(current){
                /*console.log('Current: ', current);*/
            }
        };
        const dataLen3 = this.state.data[0] && this.state.data[0].cities[0].areas.length;
        const pagination3 = {
            total:dataLen3,
            showSizeChanger:true,
            onShowSizeChange(current,pageSize){
                /*console.log('Current: ', current, '; PageSize: ', pageSize);*/
            },
            onChange(current){
                /*console.log('Current: ', current);*/
            }
        };
        let _selectedRowKeys = [];
        let _selectedRowKeys2 = [];
        const _this = this;
        const rowSelection1 = {
            onChange(selectedRowKeys, selectedRows) {
                _selectedRowKeys = [];
                _selectedRowKeys.push(selectedRowKeys);
                console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                for(let i=0; i<_this.state.data.length; i++){
                    if(_this.state.data[i].id == selectedRowKeys){
                        _selectedRowKeys2 = _this.state.data[i].cities[0].id;
                        _this.setState({ city:_this.state.data[i].cities });
                        if(_this.state.data[i].cities[0].areas.length > 0){
                            _this.setState({ area:_this.state.data[i].cities[0].areas });
                        }
                        else {
                            this.setState({ area:[] });
                        }
                        break;
                    }
                }
            },
            onSelect(record, selected, selectedRows) {
                //console.log(record, selected, selectedRows);
            },
            type: 'radio'
            //selectedRowKeys: _selectedRowKeys
        };
        const rowSelection2 = {
            onChange(selectedRowKeys, selectedRows) {
                _selectedRowKeys2 = [];
                _selectedRowKeys2.push(selectedRowKeys);
                console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                for(let i=0; i<_this.state.city.length; i++){
                    if(_this.state.city[i].id == selectedRowKeys){
                        _selectedRowKeys2 = _this.state.city[i].id;
                        _this.setState({ area:_this.state.city[i].areas });
                        break;
                    }
                }
            },
            onSelect(record, selected, selectedRows) {
                console.log(record, selected, selectedRows);
            },
            type: 'radio'
            //selectedRowKeys: _selectedRowKeys2
        };
        /*
        * bordered title={ () => { return <Button onClick = {this.addData.bind(this)}>新建省</Button>; } }
        * bordered title={() => { return <Button onClick = {this.addData.bind(this)}>新建市</Button>; }}
        *  bordered title={() => { return  <Button onClick = {this.addData.bind(this)}>新建区</Button>; }}
        * */
        return(
            <div id="region">
                
                <Table bordered size="small" columns={columns} rowKey={record => record.id} rowSelection={rowSelection1} dataSource={this.state.data} pagination={pagination1}/>

                <Table bordered size="small" columns={columns} rowKey={record => record.id} rowSelection={rowSelection2} dataSource={this.state.city && this.state.city} pagination={pagination2}/>

                <Table bordered size="small" columns={columns} rowKey={record => record.id} dataSource={this.state.area && this.state.area} pagination={pagination3}/>
                <FormRegion
                    user = {this.state.user}
                    visible = {this.state.visible}
                    title = {this.state.title}
                    confirmLoading = {this.state.confirmLoading}
                    targetData = {this.state.targetData}
                    data = {this.state.data}
                    city = {this.state.city}
                    area = {this.state.area}
                    onCancel = {this.onCancel.bind(this)}
                    dispatch = {this.props.dispatch}
                    id = {this.state.id}
                    reFetch = {this.reFetch}
                />
            </div>
        )
    };
}
let Region;
export default Region = connect((state) => {
    const {user} = state.rootReducer;
    return {user}
})(_Region);